package com.tracy.lifeproject.discovery.goods.model;

import android.os.Handler;

import com.google.gson.Gson;
import com.tracy.lifeproject.bean.GoodsBean;


import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ZJS on 2016/7/20.
 */
public class GoodsModelImpl implements GoodsModel {
    @Override
    public void loadDatas(String url, final OnResultListener listener) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mhandler.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onFailure();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                final GoodsBean goodsBean = new Gson().fromJson(result, GoodsBean.class);
                mhandler.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onSuccess(goodsBean.getData().getCategories());
                    }
                });
            }
        });
    }
    Handler mhandler = new Handler();

}
